<?php
namespace app\model;

/**
 * Created by 底片云
 * Desc: 积分模型
 * User: cbw
 * Date: 2020/11/21
 */

//load_func('logging');
class Points{

    /**
     * Desc:插入积分记录
     * User: cbw
     * Time: 2020/11/21 11:51 下午
     * @param $data
     * @return mixed
     */
    public  static  function getCheckLotteryOrPoints($lottery,$config,$system){
        return true;
    }
    public  static  function insertPointsFlag($data)
    {
        $data['updated_at']=date("Y-m-d H:i:s");
        $res = $insertid = db_insert(t_points_flag,$data);
        return $res;
    }

    /**
     * Desc:获取全部以及制定类型的积分次数
     * User: cbw
     * Time: 2020/11/21 11:58 下午
     * @param $uid
     * @param $type
     * @param $themeid
     * @return int
     */
    public static function getOpTypeNum($uid,$op,$themeid,$time='',$op_type=1)
    {
        $sql = "select count(*) as cnt from ".tablename(t_points_flag);
        if (empty($time)){
            $sql .=  " where op_type='".$op."' and uid=".$uid.
                " and themeid=".$themeid." and type=".$op_type;
            $flags = intval(db_find($sql)['cnt']);
        }else{
            $sql .=  " where op_type='".$op."' and uid=".$uid.
                " and themeid=".$themeid." and today="."'".$time."'"." and type=".$op_type;
            $flags = intval(db_find($sql)['cnt']);
        }
        return $flags;
    }

    /**
     * Desc:获取用户的积分总和
     * User: cbw
     * Time: 2020/11/22 12:08 上午
     * @param $uid
     * @param $themeid
     * @return mixed
     */
    public static function getUserPointsByUid($uid,$themeid)
    {
        $sql = "select SUM(op_num) from ".tablename(t_lot_record)." where uid=".$uid." and themeid=".$themeid;
        $res = db_query($sql);
        return $res;
    }

    /**
     * Desc:获取用户可用增加积分的方法
     * User: cbw
     * Time: 2020/11/22 1:25 上午
     * @param $uid
     * @param $type
     * @param $themeid
     * @param $config
     * @return array
     */
    public static function getUserPointsOpList($uid,$themeid,$config)
    {
        $list = [];
        $now_time = time();
        $today = date("Y-m-d",time());
        $all_chance_points_list = getPointsRulesList('all');

        foreach ($all_chance_points_list as $k =>$val)
        {
            $tips='';
            $flag = self::getOpTypeNum($uid,$k,$themeid);
            if ($k == 'pointsquan' && $config['pointsquan']>0){
                if ($config['pointsquanday']==0 ){
                    $today_flag = self::getOpTypeNum($uid,$k,$themeid,$today);
                    if($today_flag==1){
                        $tips='每天可分享1次,今日已完成明日再来';
                    }else{
                        $tips='每天可分享1次';
                    }
                    array_push($list,getPointsRulesList('pointsquan',$config,false,$tips,1,$today_flag));
                }
                if ( $config['pointsquanday']>0){
                    $remain = $config['pointsquanday'] - $flag;
                    $today_flag = self::getOpTypeNum($uid,$k,$themeid,$today);
                    if($today_flag==1){
                        if ($remain>0){
                            $tips='今日已完成分享,明日可继续';
                        }else{
                            $tips='最多可分享'.$config['pointsquanday'] . '次，您已完成';
                        }
                    }else{
                        if ($remain<=0){
                            $tips='最多可分享'.$config['pointsquanday'] . '次，您已完成';
                        }else{
                            $tips='每天可分享1次，最多'.$config['pointsquanday'] . '次';
                        }
                    }
                    array_push($list,getPointsRulesList('pointsquan',$config,false,$tips,$remain,$today_flag));
                }
            }
            if ($k=='pointsqun' && $config['pointsqun']>0 && $config['pointsqunday']>0){
//                if ($config['pointsqunday']==0){
//                    array_push($list,getPointsRulesList('pointsqun',$config,true,$tips));
//                }else{
                $remain = $config['pointsqunday'] - $flag;
                if ($remain>0){
                    $tips='最多可分享'.$config['pointsqunday'] . '次，您还有次'.$remain .'机会';
                }else{
                    $tips='最多可分享'.$config['pointsqunday'] . '次，您已完成';
                }
                array_push($list,getPointsRulesList('pointsqun',$config,false,$tips,$remain));
//                }
            }
            if ($k == 'pointsview' && $config['pointsview']>0 && $config['pointsviewmax']>0)
            {
                if ($flag<$config['pointsviewmax']){
                    $remain = $config['pointsviewmax'] - $flag;
                    $tips='好友通过您分享的链接进入活动';
                    array_push($list,getPointsRulesList('pointsview',$config,false,$tips,$remain));
                }else{
                    $tips='最多可邀请'.$config['pointsviewmax'] . '位好友，您已完成';
                    array_push($list,getPointsRulesList('pointsview',$config,false,$tips,0));
                }
            }
            if ($k == 'pointsselfbw' && $config['pointsselfbw']>0){
                if ($config['first_buy_begintime']<=$now_time && $now_time <$config['first_buy_endtime']){
                    $tips= '您在'. date("Y-m-d",$config['first_buy_endtime']) .'前下单抢购';
                }else{
                    $tips = '您自己下单抢购';
                }
                array_push($list,getPointsRulesList('pointsselfbw',$config,true,$tips));
            }
            if ($k == 'pointsfriendzc' && $config['pointsfriendzc']>0){
                if ($config['first_buy_begintime']<=$now_time && $now_time <$config['first_buy_endtime']){
                    $tips= '好友通过您分享的链接，在'. date("Y-m-d",$config['first_buy_endtime']) .'前下单抢购';
                }else{
                    $tips = '好友通过您分享的链接下单抢购';
                }
                array_push($list,getPointsRulesList('pointsfriendzc',$config,true,$tips));
            }
        }
        return $list;
    }

    /**
     * Desc:获取指定用户的积分排名
     * User: cbw
     * Time: 2020/11/22 2:02 上午
     * @param $uid
     * @return string
     */
    public static function getUserPointsRanking($uid,$themeid)
    {
        $sql = " select count(*) as cnt from "." (select themeid,lt_points from ".tablename(t_fans).
            " ) a where a.themeid = " . $themeid . " and lt_points".
            " >= (select lt_points from (select * from ".tablename(t_fans)." ) b where b.uid=".$uid." and b.themeid=$themeid ) ";
        return db_find($sql);
    }

    /**
     * Desc:获取所有用户的积分排名
     * User: cbw
     * Time: 2020/11/22 2:01 上午
     * @return mixed
     */
    public static function getAllUserPointsRanking($page_index=1,$page_size=10)
    {
        global $_P;
//        $sql = "select a.avatar,a.nickname,a.lt_points, CASE".
//        " WHEN @rowtotal = a.lt_points THEN @rownum".
//        " WHEN @rowtotal := a.lt_points THEN @rownum :=@rownum +1".
//        " WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1".
//        " END AS rownum FROM (SELECT avatar,nickname,lt_points FROM ".tablename(t_fans).
//        " ORDER BY lt_points DESC limit 10) AS a, (SELECT @rownum := 0 ,@rowtotal := NULL) r";
        $sql = "SELECT * FROM ".tablename(t_fans).
            " where themeid = " .$_P['themeid']. " and avatar!='' and nickname !='' ORDER BY lt_points DESC limit ".($page_index-1)*$page_size.','.$page_size;;
        return db_select($sql);
    }

    /**
     * Desc:获取用户积分大于0的数量
     * User: cbw
     * Time: 2020/11/22 2:22 上午
     * @return mixed
     */
    public static function getAllUserByPointsEqZero()
    {
        $sql = "select count(*) as cnt from ".tablename(t_fans)." where avatar!='' and nickname !='' ORDER BY lt_points DESC";
        return db_find($sql);
    }

    /**
     * Desc:获取指定用户的积分操作记录
     * User: cbw
     * Time: 2020/11/24 11:54 上午
     * @param $uid
     * @param $themeid
     */
    public static function getUserChancePointsFlag($uid,$themeid,$limit)
    {
        $sql = "select * from ".tablename(t_points_flag)." where uid = $uid and themeid=$themeid order by created_at desc LIMIT $limit";
        $res = db_select($sql);
        return $res;
    }

    /**
     * Desc:执行积分增改操作 记录表以及 用户积分
     * User: cbw
     * Time: 2020/11/25 5:38 下午
     * @param $p_type
     * @param $op
     * @param $fans
     * @param $themeid
     */
    public static function formatPointsDataAndAction($p_type,$op,$fans,$themeid,$avatar='')
    {
        $config =  Theme::getConfig($themeid);
        $change_points = (int)$config[$p_type];
        if ($change_points>0){
            $username = $fans['username']!=''?$fans['username']:$fans['nickname'];
            $username = mb_substr($username,0,5,'utf-8');
            if ($op==1){
                $new_points = $fans['lt_points'] + $change_points;
                $op_num = $change_points;

                if ($p_type=='pointsquan'){
                    $op_notice='转发朋友圈';
                }elseif ($p_type=='pointsqun'){
                    $op_notice='转发微信群';
                }elseif ($p_type=='pointsview'){
                    $op_notice='好友【'.$username.'】到访';
                }elseif ($p_type=='pointsselfbw'){
                    $op_notice='霸王抢';
                }elseif ($p_type=='pointsselfzc'){
                    $op_notice='下单抢购';
                }elseif ($p_type=='pointsfriendbw'){
                    $op_notice='好友【'.$username.'】霸王抢';
                }elseif ($p_type=='pointsfriendzc'){
                    $op_notice='好友【'.$username.'】下单抢购';
                }
            }
            if ($op==2){
                if ($fans['lt_points']-$change_points>0){
                    $new_points = $fans['lt_points']-$change_points;
                    $op_num = (-1 * $change_points);
                }else{
                    $new_points = 0;
                    $op_num = -$change_points;
                }

                if ($p_type=='pointsselfbw' || $p_type=='pointsselfzc'){
                    $op_notice='定单退款';
                }elseif ($p_type=='pointsfriendbw' || $p_type=='pointsfriendzc'){
                    $op_notice='好友【'.$username.'】定单退款';
                }
            }
            $points_data = [
                'uid'=>$fans['uid'],
                'op_type'=>$p_type,
                'type'=>$op,
                'op_num'=>$op_num,
                'op_notice'=>$op_notice,
                'themeid'=>$themeid,
                'today'=>date("Y-m-d",time()),
                'avatar'=>$fans['avatar']
            ];
            self::insertPointsFlag($points_data);
            Lottery::updateFansInfo($fans['uid'],['lt_points'=>$new_points]);
        }

    }


    /**
     * Desc:获取今日积分记录数量
     * User: cbw
     * Time: 2020/11/27 10:16 下午
     * @param $op_type
     * @param $uid
     * @param $themeid
     * @param int $op
     * @return int
     */
    public static function getTodayPointsFlag($op_type,$uid,$themeid,$op=1)
    {
        $now_today = date("Y-m-d",time());
        $sql = " select count(*) as cnt from ". tablename(t_points_flag)." where op_type='$op_type' and type=$op and uid='{$uid}' and themeid=$themeid and today="."'"."$now_today"."'";
        return intval(db_find($sql)['cnt']);
    }

    /**
     * Desc:获取积分记录列表 分页 排序 列表 搜索
     * User: cbw
     * Time: 2020/11/27 10:15 下午
     * @param $themeid
     * @param string $nickname
     * @param string $start_day
     * @param string $end_day
     * @return mixed
     */
    public static function getPointsOrSearchFlag($themeid,$nickname='',$start_day='',$end_day='')
    {
        $condition = " where a.themeid=$themeid order by a.created_at desc";
        if ($nickname){
            $condition = " where a.themeid=$themeid and b.nickname like '".$nickname."' order by a.created_at desc";
        }
        if ($start_day && $end_day){
            $condition = " where a.themeid=".$themeid." and a.created_at between '".$start_day."' and '".$end_day."' order by a.created_at desc";
        }
        $sql = "select a.p_id,a.uid,a.created_at,a.type,a.op_type,a.op_num,b.username,b.avatar,b.nickname,b.mobile from ".tablename(t_points_flag).
            " as a LEFT JOIN". tablename(t_fans)." as b on a.uid=b.uid".$condition;
        return db_select($sql);
    }

    /**
     * Desc:通过积分记录id获取积分记录信息
     * User: cbw
     * Time: 2020/11/27 10:15 下午
     * @param $id
     * @return mixed
     */
    public static function getPointsInfoById($id)
    {
        $res = db_get(t_points_flag,['p_id'=>$id]);
        return $res;
    }

    /**
     * Desc:controller model 调用增加、减少 积分和抽奖次数 的方法
     * User: cbw
     * Time: 2020/11/27 10:29 下午
     * @param $op       [int     required    1增加  2减少]
     * @param $op_type  [string  required    self_look 未报名 self_pay 自己下单 friend_look 好友到访 friend_pay 好友下单 share_moments 朋友圈 share_qun 群]
     * @param $new_user [bool    required    true 新用户(从未打开过活动链接)  false非新用户]
     * @param $themeid  [int     required    需要校验过合法性 ]
     * @param $system   [array   required    system]
     * @param $fans     [array   required    fans]
     * @param $is_bw     [bool   no-required    订单退款扣除类型 霸王 true 正常 false]
     * @return array    [demo ['code'=>200,'msg'=>'操作说明信息','data'=>[结果集]]]
     */
    public static function changeLotteryOrPoints($op,$op_type,$new_user,$themeid,$system,$fans,$is_bw=false)
    {

        $response = modelShow(40000);
        try {
            $type = getOpType($op_type);

            if (!$type){
                return $response;
            }
            $theme = Theme::getThemeById($themeid);
            if (!$theme){
                return  modelShow(40002);
            }
            $config =   Theme::getConfig($themeid);
            //判断抽奖 抽奖是否开启 是否在时间范围内

            if ($type=='all'||$type=='lottery'){
                $lottery_check = Points::getCheckLotteryOrPoints('lottery',$config,$system);
                if ($lottery_check==2){
                    $response = modelShow(40030);
                }
                if ($lottery_check==3){
                    $response = modelShow(40031);
                }
                if ($lottery_check==4){
                    $response = modelShow(40032);
                }
                if ($type=='lottery'){
                    $points_check =1;
                }
            }


            if ($type=='all' || $type=='points'){
                //判断积分 积分是否开启 是否在时间范围内
                $points_check = Points::getCheckLotteryOrPoints('points',$config,$system);
                if ($points_check==2){
                    $response = modelShow(40040);
                }
                if ($points_check==3){
                    $response = modelShow(40041);
                }
                if ($points_check==4){
                    $response = modelShow(40042);
                }
                if ($type=='points'){
                    $lottery_check =1;
                }
            }

            if ($points_check==1 && $lottery_check==1){
                $l_type = getLotteryOrPointsType($op_type,$config)['l_type'];
                $p_type = getLotteryOrPointsType($op_type,$config)['p_type'];
                //积分
                if ($op_type=='friend_look' && $config['pointsview']>0){
                    //判断好友到访上限
                    $pointsviewmax = (int)$config['pointsviewmax'];
                    $flag = Points::getOpTypeNum($fans['uid'],$p_type,$themeid);
                    if ($pointsviewmax>$flag && ($config['pointsviewtype']==0 || ($config['pointsviewtype']==1 && $new_user))){
                        Points::formatPointsDataAndAction($p_type,$op,$fans,$themeid);
                    }


                    $lottery_view_max = (int)$config['fanpailimit'];
                    $user_lottery_num = $fans['lt_counter'];
                    //判断用户抽奖次数未达到上限
                    if ($user_lottery_num<$lottery_view_max){
                        //查找用户到访未标记的数量
                        $flag_num = Lottery::getLtFriendNoUsedNum($themeid,$fans['uid']);
                        if ($config['lotteryviewtype']==1 && $new_user){
                            //先判断好友到访记录是否大于等于设定的数值
                            $set_lotteryview = $config['lotteryview'];
                            if ($set_lotteryview>0){
                                //加入一次抽奖机会记录
                                Lottery::formatLotteryDataAndAction($l_type,$op,$fans,$themeid);
                            }
                        }
                    }

                }
                if ($op_type=='share_qun' && $config['pointsqun']>0){
                    $pointsqunday = $config['pointsqunday'];
                    $flag = Points::getOpTypeNum($fans['uid'],$p_type,$themeid);
                    if (($pointsqunday>0 && $pointsqunday>$flag) || $pointsqunday==0){
                        Points::formatPointsDataAndAction($p_type,$op,$fans,$themeid);
                    }
                }
                //抽奖+积分
                if ($op_type=='self_pay'||$op_type=='friend_pay') {
                    if ($op==2){
                        if ($is_bw && $op_type=='self_pay'){
                            $p_type='pointsselfbw';
                        }
                        if ($is_bw && $op_type=='friend_pay'){
                            $p_type='pointsfriendbw';
                        }
                        if (!$is_bw && $op_type=='self_pay'){
                            $p_type='pointsselfzc';
                        }
                        if (!$is_bw && $op_type=='friend_pay'){
                            $p_type='pointsfriendzc';
                        }
                    }
                    Points::formatPointsDataAndAction($p_type,$op,$fans,$themeid);
                    Lottery::formatLotteryDataAndAction($l_type,$op,$fans,$themeid);
                }
                //盆友圈
                if ($op_type=='share_moments'){
                    $points_flag = Points::getOpTypeNum($fans['uid'],$p_type,$themeid);
                    $today_points_flag = Points::getTodayPointsFlag($p_type,$fans['uid'],$themeid);
                    if ($today_points_flag==0 && ( ($config['pointsquanday']==0) || ($config['pointsquanday']>0 &&$points_flag < $config['pointsquanday']))){
                        Points::formatPointsDataAndAction($p_type,$op,$fans,$themeid);
                    }
                    Lottery::formatLotteryDataAndAction($l_type,$op,$fans,$themeid);
                }
                $response = modelShow(200);
            }
        }catch (Exception $e){
            $params = ['type'=>$type,'op'=>$op,'op_type'=>$op_type,'new_user'=>$new_user,'themeid'=>$themeid,'system'=>$system,'fans'=>$fans];
            logging_run('错误日志:Points-model-changeLotteryOrPoints[参数：'.json_encode($params).'-错误信息:'.$e->getMessage());
        }
        logging_run('日志:Points-model-changeLotteryOrPoints[参数：'.json_encode($params).'-返回信息:'.$response);
        return $response;
    }

}